import { useState, useEffect, useContext } from 'react';
import { NavBar, Popup, List, Button, InfiniteScroll, Checkbox, DotLoading } from 'antd-mobile';

import AvatarImage from '../AvatarImage';

import { MySdkStoreContext } from '../../context';
import { ConversationType } from '../../constants';

import './style.scss';

interface PropsType {
  visible: boolean,
  title: string;
  cid: string;
  batchType: string,
  onOk: (selectedItem: string[], allInfoItems: any[]) => void;
  onClose: () => void;
}

export default function(props: PropsType) {
  const mySdkStore = useContext(MySdkStoreContext);
  const myUserId = mySdkStore.mockConfig.userId;
  const { visible, title, batchType, onOk, onClose } = props;
  const [selectedSingle, setSelectedSingle] = useState([]);
  const [list, setList] = useState([]);
  const [pagination, setPagination] = useState({ pageIndex: 1, totalPage: 1 });

  // 获取列表
  const getList = async (pageIndex) => {
    // 如果是”工作通知“获取会话列表，如果是”单聊通知“获取用户列表
    const getListApi = batchType === ConversationType.Notify ? 'queryConversationList' : 'queryUsers';
    const data = await mySdkStore.sdk[getListApi]({ type: 'all', pageIndex, pageSize: 20 });
    const { totalPage } = data;
    // 统一展示数据来源
    let newList = (data.rows || data.list || []).map(item => ({
      ...item,
      value: batchType === ConversationType.Notify ? item.cid : item.userId,
      label: batchType === ConversationType.Notify ? item.sessionName : item.userName || item.nickName || item.userId,
      avatarUrl: batchType === ConversationType.Notify ? item.subAvatarUrl || item.logoUrl : item.avatarUrl,
    }));
    // 如果是单聊通知，去除”本人“
    if (batchType === ConversationType.Single) {
      newList = newList.filter(item => item.id !== myUserId)
    }
    setList(pageIndex === 1 ? newList : [...list, ...newList]);
    setPagination({ pageIndex, totalPage });
  }

  useEffect(() => {
    getList(1);
  }, []);

  // 点击”确认"事件，调用传入的onOk回调
  const handleOk = () => {
    const items = [...selectedSingle];
    const allInfoItems = list.filter(item => items.includes(item.value));
    onOk(items, allInfoItems);
  }

  // 渲染列表数据
  const renderList = () => {
    return <List style={{ '--border-inner': 0 }}>
      {list.map(item => {
        return <List.Item
          key={item.value}
          prefix={
          <>
            <Checkbox value={item.value} style={{ marginRight: 12, marginBottom: 10 }} />
            <AvatarImage
              src={item.avatarUrl}
              style={{ display: 'inline-block', borderRadius: 8 }}
              fit='cover'
              width={36}
              height={36}
              nickName={item.label}
            />
        </>}>{ item.label }</List.Item>
      })}
    </List>
  }

  return visible ? <Popup
    visible
    bodyClassName="popupbody" style={{ '--z-index': 999 }}>
      <div className="selectGroupContractorComponent">
        <NavBar onBack={onClose} style={{ background: '#fff', border: 'none' }}>{ title }</NavBar>
        <Checkbox.Group onChange={(val) => setSelectedSingle(val)}>
          {renderList()}
          <InfiniteScroll loadMore={() => getList(pagination.pageIndex + 1)} hasMore={pagination.pageIndex < pagination.totalPage}>
            {pagination.totalItemCount > list.length ? (
                <>
                  <span>Loading</span>
                  <DotLoading />
                </>
              ) : ''}
          </InfiniteScroll>
        </Checkbox.Group>
        <div className="bottomOperationBar">
          <div style={{ lineHeight: '29px' }}>已选择：{selectedSingle.length}人</div>
          <Button color="primary" size="small" onClick={handleOk} disabled={!selectedSingle.length }>确定</Button>
        </div>
      </div>
  </Popup> : null;
}